import * as THREE from 'three'
import { Mesh, MeshNormalMaterial } from 'three'
import createApp from '../../core'

function createConeGeometry (dom: HTMLElement) {
  const { camera, scene, update, gui } = createApp(dom)
  camera.position.set(0, 0, 50)
  camera.lookAt(scene.position)

  const mesh = createConeFromGeometry()
  mesh.position.x = -30
  scene.add(mesh)

  const bufferMesh = createConeFromBufferGeometry()
  bufferMesh.position.x = 30
  scene.add(bufferMesh)

  update((time: number) => {
    const angle = time / 1000
    mesh.rotation.set(angle, angle, 0)

    bufferMesh.rotation.set(angle, angle, 0)
  })

  function updateMeshs () {
    generateGeometry(mesh)
    generateGeometry(bufferMesh)
  }

  gui.add(data, 'radius', 0, 30).onChange(updateMeshs)
  gui.add(data, 'height', 0, 30).onChange(updateMeshs)
  gui.add(data, 'radialSegments', 1, 30, 1).onChange(updateMeshs)
  gui.add(data, 'heightSegments', 1, 30, 1).onChange(updateMeshs)
  gui.add(data, 'openEnded').onChange(updateMeshs)
  gui.add(data, 'thetaStart', 0, Math.PI * 2).onChange(updateMeshs)
  gui.add(data, 'thetaLength', 0, Math.PI * 2).onChange(updateMeshs)
}

const data = {
  radius: 10,
  height: 20,
  radialSegments: 10,
  heightSegments: 1,
  openEnded: false,
  thetaStart: 0,
  thetaLength: Math.PI * 2
}

function createConeFromGeometry () {
  const { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength } = data
  const geometry = new THREE.ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength)
  const material = new MeshNormalMaterial({ wireframe: true })
  const mesh = new Mesh(geometry, material)
  return mesh
}

function createConeFromBufferGeometry () {
  const { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength } = data
  const geometry = new THREE.ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength)
  const material = new MeshNormalMaterial({ side: THREE.DoubleSide })
  const mesh = new Mesh(geometry, material)
  return mesh
}

function generateGeometry (mesh: THREE.Mesh) {
  const { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength } = data
  const geometry = new THREE.ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength)
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createConeGeometry
}
